import '../index.less';
import React from 'react';
import { Row, Col, Tabs, message } from 'antd';
import { JSEncrypt } from 'jsencrypt';
import { createHashHistory } from 'history';
import FormSimple from 'edframe/components/form-simple';
import xhr from 'edframe/utils/xhr';

const history = createHashHistory();
const { TabPane } = Tabs;

export default class Register extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loginConfig: [
                {
                    name: '用户名',
                    key: 'username',
                    type: 'input',
                    inputType: '',
                    prefixIconType: 'user',
                    rules: [{ type: 'required', message: '用户名不能为空' }]
                }, {
                    name: '密码',
                    key: 'password',
                    type: 'input',
                    inputType: 'password',
                    prefixIconType: 'lock',
                    rules: [{ type: 'required', message: '密码不能为空' }]
                },
                { name: '登录', key: 'login', type: 'button', btnType: '', toValidate: true }
            ],
            formConfig: [
                {
                    name: '邮箱',
                    key: 'username',
                    type: 'input',
                    inputType: 'email',
                    prefixIconType: 'mail',
                    rules: [{ type: 'required', message: '邮箱不能为空' }, { type: 'email', message: '邮箱格式不正确' }]
                }, {
                    name: '密码',
                    key: 'password',
                    type: 'input',
                    inputType: 'password',
                    prefixIconType: 'lock',
                    rules: [{ type: 'required', message: '密码不能为空' }, { type: 'password', message: '密码格式为8-16位数字字母组合' }]
                }, {
                    name: '重复密码',
                    key: 'repassword',
                    type: 'input',
                    inputType: 'password',
                    prefixIconType: 'lock',
                    rules: [{ type: 'customize', message: '两次密码输入不一致', validator: () => this.validateRePsd() }]
                },
                { name: '注册', key: 'register', type: 'button', btnType: '', toValidate: true }
            ],
            loginData: {},
            registerData: {},
            curTab: '1', // 当前标签页
        };
    }

    componentWillMount() {
        xhr.get('common.getPublicKey', {}, (res) => {
            if (res.success) {
                this.rsa = res.data;
            }
        });
    }

    onEventHandler(e) { // 表单事件
        console.log('表单', e);
        let { item, type, value, validate } = e,
            { curTab } = this.state;
        switch (item.key) {
            case 'login':
                console.log('登录', e)
                validate && this.submit('login');
                break;
            case 'register':
                validate && this.submit('register');
                break;
            default:
                break;
        }
        let form = curTab === '1' ? 'loginData' : 'registerData';
        switch (type) {
            case 'change':
                this.setState(prevState => ({ [form]: { ...prevState[form], [item.key]: value } }));
                break;
            default:
                break;
        }
    }

    validateRePsd() { // 校验两次密码是否一致
        let { password, repassword } = this.state.registerData,
            flag = false;
        if (password === repassword) {
            flag = true;
        }
        return flag;
    }

    submit(type) { // 注册/登录
        let { username, password } = this.state[`${type}Data`],
            { publicKey, keyIndex } = this.rsa,
            encrypt = new JSEncrypt();
        encrypt.setPublicKey(publicKey);
        xhr.post(`reglog.${type}`, {
            username,
            password: encrypt.encrypt(password),
            keyIndex
        }, (res) => {
            console.log('submit', res)
            if (res.success) {
                switch (type) {
                    case 'register':
                        message.success('注册成功，请登录！');
                        this.setState({ curTab: '1' });
                        break;
                    case 'login':
                        history.push('/home');
                        break;
                    default:
                        break;
                }
            } else {
                message.error(res.message || '操作失败！');
            }
        });
    }

    render() {
        let { loginData, loginConfig, registerData, formConfig, curTab } = this.state;
        return (
            <div>
                <Row>
                    <Col className="flx-center" span={12}>
                        <img alt="EDaily" src={require('static/logo/edaily_logo_400_px_transparent_blue.png')} />
                    </Col>
                    <Col span={12}>
                        <div className="line-v" />
                        <Row className="mt-80">
                            <Col offset={7} span={10}>
                                <Tabs activeKey={curTab} defaultActiveKey="1"
                                    onChange={(e) => this.setState({ curTab: e })}
                                >
                                    <TabPane key="1" tab="登录">
                                        <FormSimple dataSource={loginData} eventHandler={(e) => this.onEventHandler(e)}
                                            formConfig={loginConfig}
                                        />
                                    </TabPane>
                                    <TabPane key="2" tab="注册">
                                        <FormSimple dataSource={registerData}
                                            eventHandler={(e) => this.onEventHandler(e)} formConfig={formConfig}
                                        />
                                    </TabPane>
                                </Tabs>
                            </Col>
                        </Row>
                    </Col>
                </Row>
            </div>
        );
    }
}
export { Register };
